package com.heima.kafka.sample;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/25
 */
public class ProducerQuickStart {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //1.kafka的配置信息
        Properties properties = new Properties();
        //kafka的连接地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"192.168.200.130:9092");
        //发送失败，失败的重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,5);
        //数据压缩
        properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"snappy");
        //消息key的序列化器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //消息value的序列化器
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //2.生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);
        //3.发送消息
        for (int i = 0; i < 10; i++) {
            //封装发送的消息   topic key value
//            ProducerRecord<String,String> record = new ProducerRecord<String, String>("itheima-topic","100001","hello kafka");
            String[] arr = {"kafkaStream", "Hadoop", "apcheStorm"};
            String value = "hello " + RandomUtil.randomEle(arr);
            ProducerRecord<String,String> record = new ProducerRecord<String, String>("itcast-topic-input", value);
            producer.send(record);
        }
        //同步发送消息
        /*RecordMetadata recordMetadata = producer.send(record).get();
        System.out.println(recordMetadata.offset());*/
        //异步发送消息
        /*producer.send(record, (recordMetadata, e) -> {
            if (ObjectUtil.isNotEmpty(e)) {
                System.err.println("记录错误日志。。。");
            }
            System.out.println(recordMetadata.offset());
        });*/
        //4.关闭消息通道，必须关闭，否则消息发送不成功
        producer.close();
    }
}
